<template>
	<div class="login"  v-loading="loading"
    element-loading-text="实验室数据初始化中..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.7)">
		<el-container >
			<el-header class="head" style = "padding-top:8px">
				<img src="../assets/img/logo.png" alt="" class="logo">
				<div class = "projectName">实验室信息管理系统</div>
			</el-header>
			<div class = "el-main" :style="{height: mainHeight}">
				<div class="mainBackground mainBackground3" >
					<!--<img src = "../assets/img/bannerr.jpg" />-->
				</div>
				<!--<div class="mainBackground mainBackground1" @mouseenter="changePhoto(1)" @mouseleave="changePhoto(-1)" v-if="isEnter">

				</div>
				<div class="mainBackground mainBackground2" @mouseenter="changePhoto(1)" @mouseleave="changePhoto(-1)" v-if="!isEnter">
				</div>-->
				<div class="register">
					<div class="content">
						<el-form :model="ruleForm" :rules="rules2" ref="ruleForm" label-width="75px" class="demo-ruleForm">
							<span style="font-size:16px"><b>账号登录</b></span>
							<el-form-item label="账号" prop="name" class="lbl">
								<el-input v-model="ruleForm.name" class="ipt"></el-input>
							</el-form-item>
							<el-form-item label="密码" prop="password" class="lbl">
								<el-input type="password" v-model="ruleForm.password" auto-complete="off" :name="Math.random()" class="ipt" @keyup.enter.native="getPublicKey('ruleForm')"></el-input>
							</el-form-item>
              <el-form-item label="验证码" prop="code" class="lbl code">
              	<el-input v-model="ruleForm.code" class="ipt codeForm" @keyup.enter.native="getPublicKey('ruleForm')"></el-input>
                <span style="display: inline-block;" @click="changeImgCode">
                    <img id="imgCode"  style="width: 100%;height: 100%;cursor: pointer;" title="点击刷新验证码"/>
                </span>
              </el-form-item>

							<el-form-item label="" class="remberPwd">
								<el-checkbox v-model="checkedPwd">记住密码</el-checkbox>
							</el-form-item>

							<el-form-item class="btu" style="margin-bottom: 0;">
								<el-button type="primary" @click="getPublicKey('ruleForm')"  style="width:100%;" :disabled = "!isRepeat">登录</el-button>
								<!--<el-button @click="resetForm('ruleForm')">重置</el-button>-->
							</el-form-item>
						</el-form>
					</div>
				</div>
			</div>
		</el-container>
		<div class="version">
      版本: {{versionData}}  &nbsp;&nbsp;&nbsp;<span style="letter-spacing: 1px;">推荐使用谷歌浏览器</span></div>
		<!---->
		<select-dep :addVisible.sync="chooseDep" :labData="labData"></select-dep>
	</div>
</template>

<script>
  import $ from 'jquery'
	import selectDep from './selectDep.vue'
	import { mapState } from 'vuex'

	export default {
		name: "login",
		data() {
			return {
        imgCode:"",
				chooseDep: false, //选择实验室弹框是否弹出
				ruleForm: {
					name: '',
					password: '',
          code:"",
				},
				rules2: {
					name: [{
						required: true,
						message: '请输入账号',
						trigger: 'blur'
					}],
					password: [{
						required: true,
						message: '请输入密码',
						trigger: 'blur'
					}],
          code:[{
						required: true,
						message: '请输入验证码',
						trigger: 'blur'
					}]
				},
				description: '',
				labData: [], //实验室信息
				errorClass: '',
				isEnter: true,
				checkedPwd: false,
				isRepeat:true,
				versionData:"",
        uid:"",
        loading:false,
			};
		},
		components: { selectDep },
		computed: {
			...mapState([]),
			// el-main
			mainHeight(){
				return (window.innerHeight - 110) + "px";
			}
		},
    created() {
      localStorage.setItem('isFrom',"selfLogin");
    },
		mounted(){

			this.getCookie();
			this.getVersion();
      this.changeImgCode();
			var isLogin = sessionStorage.getItem('labAccountInfo');


			// if(isLogin != null){
			// 	this.$router.push('/shuisi')
			// }
		},
		methods: {
      changeImgCode(){
        console.log(this.uuid())
        this.uid = this.uuid()
        $("#imgCode").prop('src',process.env.baseUrl + 'verifyCode/getCode.htm?uid='+ this.uid)
      },

      uuid() {
      	var s = [];
      	var hexDigits = "0123456789abcdef";
      	for (var i = 0; i < 36; i++) {
      		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      	}
      	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      	s[8] = s[13] = s[18] = s[23] = "-";

      	var uuid = s.join("");
      	return uuid;
      },
			changePhoto(a) {
				if (a == -1) {
					this.isEnter = true;
				} else {
					this.isEnter = false;
				}
			},
			submitForm(data1){
        var data = data1;
        data.code = this.ruleForm.code;
        data.codeFlag = this.uid;
				this.$http({
							apiUrl: 'login/login.htm',
							method: 'post',
							params:data,
							isJson: false
						}).then(res => {
							this.isRepeat = true;
							if (res.code == 0) {
                localStorage.setItem('isFrom',"selfLogin");
                sessionStorage.setItem('loginAccount',res.data);
								this.getDictionaryData();
								this.getlabAuth().then(res => {
									if (res.data.length == 1) {
										this.clickcell(res.data[0])
									} else {
										this.labData = res.data;
										this.chooseDep = true;
									}
								})
							}
              if(res.code == 11006){
                 this.ruleForm.code = ""
                 this.changeImgCode();
              }

						})


			},
			// 先把密码转化成 密文
			getPublicKey(formName) {
				this.isRepeat = false;
				let _this = this;
				this.$refs[formName].validate((valid) => {
					if (valid) {
						_this.ruleForm.name = _this.ruleForm.name;
						_this.ruleForm.password = _this.ruleForm.password;
						if (_this.checkedPwd) {
							//传入账号名，密码，和保存天数3个参数
							_this.setCookie(_this.ruleForm.name, _this.ruleForm.password, 7);
						} else {
							_this.clearCookie();
						}
					this.$http({
            apiUrl: '/getPublicKey.htm',
            method: 'post',
          }).then(res => {
            if (res.code === 0) {
							var map = res.data;
							var encrytor  = new JSEncrypt();
							encrytor.setPublicKey(map.publicKey)
							var pass = encrytor.encrypt(_this.ruleForm.password)
							var dataForm = {
									name:_this.ruleForm.name,
									key : res.data.id,
									passwordEncryp:pass,
							}
               this.submitForm(dataForm)
            }
          })

					} else {
						this.isRepeat = true;
						return false;
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
			//设置cookie
			setCookie(c_name, c_pwd, exdays) {
				var exdate = new Date(); //获取时间
				exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
				//字符串拼接cookie
				window.document.cookie = "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
				window.document.cookie = "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
			},
			//读取cookie
			getCookie: function () {

				if (document.cookie.length > 0) {
					this.checkedPwd = true;
					var arr = document.cookie.split('; '); //这里显示的格式需要切割一下自己可输出看下
					for (var i = 0; i < arr.length; i++) {
						var arr2 = arr[i].split('='); //再次切割
						//判断查找相对应的值
						if (arr2[0] == 'userName') {
							this.ruleForm.name = arr2[1]; //保存到保存数据的地方
						} else if (arr2[0] == 'userPwd') {
							this.ruleForm.password = arr2[1];
						}
					}
				}
			},
			//清除cookie
			clearCookie: function () {
				this.setCookie("", "", -1); //修改2值都为空，天数为负1天就好了
			},
			// 登陆成功后获取实验室(未完成)
			getlabAuth() {
				return new Promise((resolve, reject) => {
					this.$http({
						apiUrl: 'login/getlabAuth.htm',
						method: 'post',
					}).then(res => {
						if (res.code == 0) {
							resolve(res)
						}

					})
				})
			},
			getVersion(){
				this.$http({
						apiUrl: '/version.htm',
						method: 'post',
					}).then(res => {
						if (res.code == 0) {
							this.versionData = res.data
						}

					})
			},
			clickcell(val) {
        this.loading = true;
				this.$http({
					apiUrl: 'login/chooselab.htm',
					method: 'post',
					params: { id: val.id,mark:val.mark },
					isJson: false
				}).then(res => {
          this.loading = false;
					if (res.code === 0) {
						sessionStorage.setItem("defaultlabData", JSON.stringify(val));
						this.$router.push('/shuisi')
						this.$store.commit('changenowpage', 'homePage');
						this.$store.state.menuName = '';
						this.$store.state.pageName = '';
						this.$store.dispatch('dogetDictionary')

					}

				})
			},
			// 登陆成功存储数据字典数据
			getDictionaryData() {

				this.$http({
					method: 'post',
					apiUrl: '/system/readDictionary.htm',
				}).then(res => {
					if (res.code == 0) {
						// console.log(res.data)
						// console.log(JSON.parse(JSON.stringify(res.data)))
						sessionStorage.setItem('dataDictionaryList', JSON.stringify(res.data));

					} else {

					}
				}).catch((err) => {

				});
			},
		}
	}

</script>

<style scoped lang='scss'>
	.login {
		.el-header {
			background-color:#fff;
			color: #333;
			line-height: 60px;
			.projectName{
				display:inline-block;
				font-size:20px;
				letter-spacing: 5px;
    			font-weight: 550;
				margin-left:10px;
				border-left:1px solid #ccc;
				height: 25px;
				line-height: 25px;
				width:250px;
				text-align:center;
				vertical-align: super;

			}
		}
		.el-aside {
			background-color: #D3DCE6;
			color: #333;
			text-align: center;
			line-height: 200px;
		}
		.el-main {
			background-color: #E9EEF3;
			color: #333;
			text-align: center;
			// height: 380px;
			// height:calc(100% - 120px);
			padding: 0px;
			position: relative;
		}
		body>.el-container {
			margin-bottom: 40px;
		}
		.logo {
			float: left;
			width:346px;
		}
		.mainBackground {
			width: 100%;
			height: 100%;
		}

		.mainBackground.mainBackground3 {
			background: url('../assets/img/bannerr.jpg')  no-repeat;
			// background-size: cover;
			// position: fixed;
			background-position: 0px 0px;
			background-size: 100% 100%;

		}
		.register {
			position: absolute;
			top: 0px;
			bottom: 0;
			right: 70px;
			width: 380px;
			height: 380px;
			overflow: hidden;
			margin: auto;
			background: rgba(255, 255, 255, .3);
		}
		.text {
			font-size: 14px;
		}
    .codeForm{
      width:50%;
      float:left;

    }
		.content {
			background: rgba(255, 255, 255, .8);
			border-radius: 4px;
			width: 360px;
			height: 360px;
			padding: 15px;
			margin: 10px auto;
			.el-form-item__content {
				margin-bottom: 10px;
			}
		}
		.item {
			padding: 18px 0;
		}
		.box-card {
			width: 480px;
		}
		ul {
			background: rgba(255, 255, 255, 0.48);
			height: 100%;
		}
		li {
			height: 10%;
			margin: 3px;
		}
		.btu {
			.el-form-item__content {
				background-color: red;
			}
		}
		.lbl {
			margin-top: 30px;
			margin-bottom: 5px;
		}
	}

	.version {
		text-align: center;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		margin: auto;
		height: 50px;
		line-height: 50px;
		background-color:#fff;
	}
</style>
<style>
	.content .el-form.demo-ruleForm .remberPwd .el-form-item__content {
		text-align: left;
		font-size: 12px;
	}

	.content .el-form.demo-ruleForm .remberPwd {
		margin-bottom: 5px;
	}
	article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary{
		display: block;
	}
</style>
